package com.game.autoTool.project.web.common;

import javax.swing.*;
import java.awt.*;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class DynamicSwingWithFastJSON {
    public static void main(String[] args) {
        // 创建主窗口
        JFrame frame = new JFrame("FastJSON 动态 Swing");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);

        // 主面板使用卡片布局
        JPanel mainPanel = new JPanel(new CardLayout());
        
        // 1. 加载界面
        JPanel loadingPanel = new JPanel(new BorderLayout());
        loadingPanel.add(new JLabel("正在加载数据...", SwingConstants.CENTER), BorderLayout.CENTER);
        mainPanel.add(loadingPanel, "loading");

        // 2. 内容界面
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        JScrollPane scrollPane = new JScrollPane(contentPanel);
        mainPanel.add(scrollPane, "content");

        // 3. 错误界面
        JPanel errorPanel = new JPanel(new BorderLayout());
        JButton retryButton = new JButton("重试");
        errorPanel.add(new JLabel("加载数据失败", SwingConstants.CENTER), BorderLayout.CENTER);
        errorPanel.add(retryButton, BorderLayout.SOUTH);
        mainPanel.add(errorPanel, "error");

        frame.add(mainPanel);
        frame.setVisible(true);

        // 初始加载数据
        loadDataAndCreateUI(contentPanel, mainPanel);

        // 重试按钮事件
        retryButton.addActionListener(e -> {
            ((CardLayout) mainPanel.getLayout()).show(mainPanel, "loading");
            loadDataAndCreateUI(contentPanel, mainPanel);
        });
    }

    private static void loadDataAndCreateUI(JPanel contentPanel, JPanel mainPanel) {
        new SwingWorker<JSONObject, Void>() {
            @Override
            protected JSONObject doInBackground() throws Exception {
                // 模拟API调用 - 实际项目中替换为真实的HTTP请求
                Thread.sleep(1500);

                // 模拟API返回的JSON数据 (使用FastJSON格式)
                String jsonResponse = "{\n" +
                        "  \"title\":\"用户信息\",\n" +
                        "  \"components\":[\n" +
                        "    {\"type\":\"label\",\"text\":\"用户信息面板\"},\n" +
                        "    {\"type\":\"textfield\",\"label\":\"用户名\",\"default\":\"张三\"},\n" +
                        "    {\"type\":\"password\",\"label\":\"密码\"},\n" +
                        "    {\"type\":\"combobox\",\"label\":\"角色\",\"options\":[\"管理员\",\"普通用户\",\"访客\"]},\n" +
                        "    {\"type\":\"checkbox\",\"label\":\"记住登录\",\"checked\":true},\n" +
                        "    {\"type\":\"radio\",\"label\":\"性别\",\"options\":[\"男\",\"女\"],\"name\":\"gender\"},\n" +
                        "    {\"type\":\"button\",\"text\":\"提交\",\"action\":\"submit\"},\n" +
                        "    {\"type\":\"table\",\"columns\":[\"ID\",\"名称\",\"价格\"],\n" +
                        "     \"data\":[[\"1\",\"商品A\",\"100\"],[\"2\",\"商品B\",\"200\"]]}\n" +
                        "  ]\n" +
                        "}";

                return JSON.parseObject(jsonResponse);
            }

            @Override
            protected void done() {
                try {
                    JSONObject data = get();
                    createUIFromJSON(contentPanel, data);
                    ((CardLayout) mainPanel.getLayout()).show(mainPanel, "content");
                } catch (Exception e) {
                    e.printStackTrace();
                    ((CardLayout) mainPanel.getLayout()).show(mainPanel, "error");
                }
            }
        }.execute();
    }

    private static void createUIFromJSON(JPanel panel, JSONObject data) {
        panel.removeAll();

        // 设置标题
        String title = data.getString("title");
        if (title != null) {
            JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
            titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
            titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
            panel.add(titleLabel);
            panel.add(Box.createRigidArea(new Dimension(0, 20)));
        }

        // 解析并创建各个组件
        JSONArray components = data.getJSONArray("components");
        for (int i = 0; i < components.size(); i++) {
            JSONObject component = components.getJSONObject(i);
            String type = component.getString("type");

            JPanel componentPanel = new JPanel();
            componentPanel.setLayout(new BoxLayout(componentPanel, BoxLayout.X_AXIS));
            componentPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

            switch (type) {
                case "label":
                    JLabel label = new JLabel(component.getString("text"));
                    label.setAlignmentX(Component.LEFT_ALIGNMENT);
                    panel.add(label);
                    break;

                case "textfield":
                    if (component.containsKey("label")) {
                        componentPanel.add(new JLabel(component.getString("label") + ": "));
                    }
                    JTextField textField = new JTextField(20);
                    String defaultValue = component.getString("default");
                    if (defaultValue != null) {
                        textField.setText(defaultValue);
                    }
                    componentPanel.add(textField);
                    panel.add(componentPanel);
                    break;

                case "password":
                    if (component.containsKey("label")) {
                        componentPanel.add(new JLabel(component.getString("label") + ": "));
                    }
                    JPasswordField passwordField = new JPasswordField(20);
                    componentPanel.add(passwordField);
                    panel.add(componentPanel);
                    break;

                case "combobox":
                    if (component.containsKey("label")) {
                        componentPanel.add(new JLabel(component.getString("label") + ": "));
                    }
                    JSONArray options = component.getJSONArray("options");

                    String[] optionsArray = null;
                    if (options == null) {
                        optionsArray = new String[0];
                    } else {
                        optionsArray = options.toArray(new String[0]);
                    }

                    JComboBox<String> comboBox = new JComboBox<>(optionsArray);
                    componentPanel.add(comboBox);
                    panel.add(componentPanel);
                    break;

                case "checkbox":
                    JCheckBox checkBox = new JCheckBox(component.getString("label"));
                    Boolean checked = component.getBoolean("checked");
                    if (checked != null && checked) {
                        checkBox.setSelected(true);
                    }
                    checkBox.setAlignmentX(Component.LEFT_ALIGNMENT);
                    panel.add(checkBox);
                    break;

                case "radio":
                    if (component.containsKey("label")) {
                        panel.add(new JLabel(component.getString("label") + ":"));
                    }
                    JSONArray radioOptions = component.getJSONArray("options");
                    ButtonGroup group = new ButtonGroup();
                    JPanel radioPanel = new JPanel();
                    radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.X_AXIS));
                    for (int j = 0; j < radioOptions.size(); j++) {
                        JRadioButton radioButton = new JRadioButton(radioOptions.getString(j));
                        if (j == 0) radioButton.setSelected(true);
                        group.add(radioButton);
                        radioPanel.add(radioButton);
                        radioPanel.add(Box.createHorizontalStrut(10));
                    }
                    radioPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
                    panel.add(radioPanel);
                    break;

                case "button":
                    JButton button = new JButton(component.getString("text"));
                    button.setAlignmentX(Component.CENTER_ALIGNMENT);
                    String action = component.getString("action");
                    if (action != null) {
                        button.addActionListener(e -> {
                            JOptionPane.showMessageDialog(panel, "执行操作: " + action);
                        });
                    }
                    panel.add(button);
                    break;

                case "table":
                    JSONArray columns = component.getJSONArray("columns");
                    JSONArray tableData = component.getJSONArray("data");


                    String[] columnArray = null;
                    if (columns == null) {
                        columnArray = new String[0];
                    } else {
                        columnArray = columns.toArray(new String[0]);
                    }

                    Object[][] dataArray = new Object[tableData.size()][];
                    for (int j = 0; j < tableData.size(); j++) {
                        JSONArray row = tableData.getJSONArray(j);
                        dataArray[j] = row.toArray();
                    }

                    JTable table = new JTable(dataArray, columnArray);
                    JScrollPane tableScroll = new JScrollPane(table);
                    tableScroll.setAlignmentX(Component.LEFT_ALIGNMENT);
                    panel.add(tableScroll);
                    break;
            }

            panel.add(Box.createRigidArea(new Dimension(0, 10)));
        }

        panel.revalidate();
        panel.repaint();
    }
}